from django.db.models import Count
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from ..models import Category
from ..serializers import (
    CategorySerializer,
    CategoryDetailSerializer,
    CategoryNavSerializer,
    CategoryTreeSerializer
)

class CategoryViewSet(viewsets.ReadOnlyModelViewSet):
    """分类视图集
    
    提供以下功能:
    - 获取导航菜单 (/nav/)
    - 获取分类树 (/tree/)
    - 获取子分类 (/{slug}/children/)
    - 获取祖先分类 (/{slug}/ancestors/)
    """
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    lookup_field = 'slug'

    def get_queryset(self):
        """获取查询集并添加文档数量统计"""
        queryset = super().get_queryset()
        return queryset.annotate(
            documents_count=Count('documents')
        )

    def get_serializer_class(self):
        """根据不同的操作返回对应的序列化器"""
        if self.action == 'retrieve':
            return CategoryDetailSerializer
        if self.action in ['nav', 'children', 'ancestors']:
            return CategoryNavSerializer
        if self.action == 'tree':
            return CategoryTreeSerializer
        return self.serializer_class

    @action(detail=False, methods=['get'])
    def nav(self, request):
        """获取顶级导航分类"""
        categories = self.get_queryset().filter(is_nav=True).order_by('nav_sort')
        serializer = self.get_serializer(categories, many=True)
        return Response({
            'code': 0,
            'message': 'success',
            'data': serializer.data
        })

    @action(detail=False, methods=['get'])
    def tree(self, request):
        """获取分类树结构"""
        categories = self.get_queryset().filter(parent=None).order_by('nav_sort')
        serializer = self.get_serializer(categories, many=True)
        return Response({
            'code': 0,
            'message': 'success',
            'data': serializer.data
        })

    @action(detail=True, methods=['get'])
    def children(self, request, slug=None):
        """获取指定分类的子分类"""
        category = self.get_object()
        children = self.get_queryset().filter(parent=category).order_by('nav_sort')
        serializer = self.get_serializer(children, many=True)
        return Response({
            'code': 0,
            'message': 'success',
            'data': serializer.data
        })

    @action(detail=True, methods=['get'])
    def ancestors(self, request, slug=None):
        """获取指定分类的所有祖先分类（包括父级）,从根分类到直接父级的顺序"""
        category = self.get_object()
        ancestors = []
        current = category.parent
        while current:
            ancestors.append(current)
            current = current.parent
        ancestors.reverse()
        serializer = self.get_serializer(ancestors, many=True)
        return Response({
            'code': 0,
            'message': 'success',
            'data': serializer.data
        })

    def list(self, request, *args, **kwargs):
        response = super().list(request, *args, **kwargs)
        return Response({
            'code': 0,
            'message': 'success',
            'data': response.data
        })

    def retrieve(self, request, *args, **kwargs):
        response = super().retrieve(request, *args, **kwargs)
        return Response({
            'code': 0,
            'message': 'success',
            'data': response.data
        }) 